package com.lpc.android.abc.base.api;

import com.lpc.android.abc.base.constants.Constants;
import com.lpc.android.abc.base.utils.LogUtil;
import com.lpc.android.abc.base.utils.NetWorkUtil;
import com.lpc.android.abc.base.utils.UIUtil;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by lpc on 2016/10/30.
 */

public class Api {

    //请求时间
    private static final int DEFAULT_TIMEOUT = 10;

    // 消息头
    private static final String HEADER_X_HB_Client_Type = "X-HB-Client-Type";
    private static final String FROM_ANDROID = "ayb-android";

//    private static Retrofit retrofit;

//    private MProgressDialog loading;

//    private static Api api = new Api();
//
//    private Api(){
//
//    }

//    public static Api getInstance(){
//        return api;
//    }

   /* public <S> S getService(Class<S> serviceClass){


        return getRetrofit().create(serviceClass);
    }*/

    private static ApiService mApiService;

    protected ApiService getApiService(){
        if (mApiService == null) {
            mApiService = getRetrofit().create(ApiService.class);
        }
        return mApiService;
    }

    /**
     * 拦截器  给所有的请求添加消息头
     */
    private static Interceptor headInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request()
                    .newBuilder()
                    .addHeader(HEADER_X_HB_Client_Type, FROM_ANDROID)
                    .build();
            return chain.proceed(request);
        }
    };

    /**
     * 拦截器  消息缓存时间-------------目前没有用
     */
    private static Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {

            Request request = chain.request();
            if (!NetWorkUtil.isConnected()) {
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }

            Response originalResponse = chain.proceed(request);
            if (NetWorkUtil.isConnected()) {
                int maxAge = 60;                  //在线缓存一分钟 60
                return originalResponse.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .build();

            } else {
                int maxStale = 60 * 60 * 24 * 7 * 4;     //离线缓存4周 60 * 60 * 24 * 7 * 4
                return originalResponse.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .build();
            }
        }
    };

    /**
     * 创建Retrofit实例
     *
     * @return
     */
    public static Retrofit getRetrofit() {

        //拦截器   拦截日志
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        //缓存目录
        File cacheFile = new File(UIUtil.getContext().getCacheDir(), "cache");
        Cache cache = new Cache(cacheFile, 50 * 1024 * 1024);//50Mb

        //okhttp设置
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(headInterceptor)
                .addInterceptor(httpLoggingInterceptor)
//                .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
//                .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
                .cache(cache)
                .build();

        //Retrofit设置
        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(Constants.API.getMeServerUrl())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        return retrofit;
    }

    /*protected <T> Observable<T> applySchedulers(Observable<T> responseObservable) {

        return responseObservable
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }*/

    /**
     * 分离线程
     *
     * @param responseObservable
     * @param <T>
     * @return
     */
    /*protected <T> Observable<T> applySchedulers(Observable<T> responseObservable) {

        return responseObservable
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap(new Func1<T, Observable<T>>() {
                    @Override
                    public Observable<T> call(T tResponse) {

                        return flatRespnse(tResponse);
                    }
                });
    }*/

    /**
     * 在没有解绑的时候才执行Subscriber中的方法
     *
     * @param tResponse
     * @param <T>
     * @return
     */
    /*private <T> Observable<T> flatRespnse(final T tResponse) {

        return Observable.create(new Observable.OnSubscribe<T>() {

            @Override
            public void call(Subscriber<? super T> subscriber) {

                if (!subscriber.isUnsubscribed()) {
                    subscriber.onNext(tResponse);
                    subscriber.onCompleted();
                }
            }
        });
    }*/

    /**
     * 页面关闭后要把回调滞空，否则容易空指针-----带进度条
     *
     * @param apiCallback
     * @param <T>
     * @return
     */
    /*protected <T> Subscriber newProgressSubscriber(final Context context, final ApiCallback<T> apiCallback) {

        return new Subscriber<T>() {

            @Override
            public void onStart() {
                super.onStart();
                if (apiCallback != null) {
                    apiCallback.onStart();
                }
//                showLoadingDialog(context);

            }

            @Override
            public void onCompleted() {

                if (apiCallback != null) {
                    apiCallback.onCompleted();
                }
//                if(!this.isUnsubscribed()){
//                    this.unsubscribe();
//                }
//                hideLoadingDialog();
            }

            @Override
            public void onError(Throwable e) {

                if (apiCallback != null) {
                    apiCallback.onError(e);
                }
//                hideLoadingDialog();
            }

            @Override
            public void onNext(T t) {

                if (apiCallback != null) {
                    apiCallback.onNext(t);
                }
            }
        };

    }*/


    /**
     * 显示进度条
     *
     * @param context
     */
   /* private void showLoadingDialog(Context context) {
        if (loading == null) {
            loading = new MProgressDialog(context, false);
        }
        loading.show();
    }*/

    /**
     * 隐藏进度条
     *
     * @param
     */
    /*private void hideLoadingDialog() {
        if (loading != null) {
            loading.dismiss();
            loading = null;
        }

    }*/
    public void onDestory() {
        LogUtil.e("api onDestory");
    }

}
